package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.service.IotEnterpriseManageRService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.IotEnterpriseManageRelService;
import com.hunttown.mes.manage.service.TransportUserManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.IotEnterpriseDTO;
import com.hunttown.mes.rpc.domain.IotEnterpriseManageDTO;
import com.hunttown.mes.rpc.domain.enums.enterprise.EnterpriseTypeEnum;
import com.hunttown.mes.rpc.domain.enums.user.UserTypeEnum;
import com.hunttown.mes.rpc.domain.query.AnalysisManageDTOQuery;
import com.hunttown.mes.rpc.domain.query.IotEnterpriseDTOQuery;
import com.hunttown.mes.rpc.domain.query.IotEnterpriseManageDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.mes.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2021-02-20 11:33:43
 */
@Controller
@RequestMapping(value = "/basic/enterprise")
public class EnterpriseController {

    private final static Logger logger = LoggerFactory.getLogger(EnterpriseController.class);

    private final IotEnterpriseManageRService iotEnterpriseService;
    private final IotEnterpriseManageRelService enterpriseRelService;
    private final AnalysisManageManageService manageService;
    private final TransportUserManageService userService;

    @Autowired
    public EnterpriseController(IotEnterpriseManageRService iotEnterpriseService, IotEnterpriseManageRelService enterpriseRelService, AnalysisManageManageService manageService, TransportUserManageService userService) {
        this.iotEnterpriseService = iotEnterpriseService;
        this.enterpriseRelService = enterpriseRelService;
        this.manageService = manageService;
        this.userService = userService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, IotEnterpriseDTOQuery dtoQuery) {

        Page<IotEnterpriseDTO> dataPage = iotEnterpriseService.getForPage(dtoQuery);
        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "basic/enterprise/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        IotEnterpriseDTO obj;

        if (id > 0) {
            obj = iotEnterpriseService.getById(id);
        } else {
            obj = new IotEnterpriseDTO();
            obj.setId(0);
        }
        model.addAttribute("Obj", obj);

        model.addAttribute("enterpriseTypList", EnterpriseTypeEnum.getEnumList());

        return "basic/enterprise/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, IotEnterpriseDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //日期转化
            objDTO.setFoundDate(DateConvertUtils.strToDate(objDTO.getFoundDateSr()));
            objDTO.setOpenStartDate(DateConvertUtils.strToDate(objDTO.getOpenStartDateSr()));
            objDTO.setOpenEndDate(DateConvertUtils.strToDate(objDTO.getOpenEndDateSr()));
            objDTO.setIssueDate(DateConvertUtils.strToDate(objDTO.getIssueDateSr()));

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = iotEnterpriseService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = iotEnterpriseService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = iotEnterpriseService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = iotEnterpriseService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        IotEnterpriseDTO obj = new IotEnterpriseDTO();
        obj.setId(id);

        if (id > 0) {
            obj = iotEnterpriseService.getById(id);
        }
        iotEnterpriseService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

    //region 用户关联企业

    /**
     * 获取企业列表，并判断用户是否已关联
     *
     * @param model    model
     * @param manageId 用户ID
     * @return vm
     */
    @RequestMapping(value = "/getEnterpriseList", method = RequestMethod.POST)
    public String getEnterpriseList(Model model, Integer manageId) {

        //1.根据 manageId 获取他已经关联的企业
        List<Integer> relEntIdList = enterpriseRelService.getEnterpriseIdByManage(manageId);

        //2.获取企业列表
        IotEnterpriseDTOQuery query = new IotEnterpriseDTOQuery();
        query.setPageSize(100);
        query.setStopFlag(0);
        Page<IotEnterpriseDTO> dataPage = iotEnterpriseService.getForPage(query);

        //3.标记已关联的企业
        for (IotEnterpriseDTO item : dataPage.getItems()) {
            if (relEntIdList.contains(item.getId())) {
                item.setIsSelect(1);
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("manageId", manageId);

        AnalysisManageDTO manageDTO = manageService.getFromCacheId(manageId);
        model.addAttribute("manageName", manageDTO == null ? "--" : manageDTO.getNickName());

        return "basic/enterprise/enterprise-list-modal";
    }

    /**
     * 保存用户关联企业
     *
     * @param manageId 用户ID
     * @param entIds   关联企业ID
     * @return map
     */
    @RequestMapping(value = "/saveRelEnterprise", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveRelEnterprise(HttpServletRequest request, Integer manageId, String entIds) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", 0);

        try {

            if (manageId == null || manageId <= 0) {
                map.put("returnMessage", "未获取到用户信息");
                return map;
            }

            //取出要操作用户信息
            AnalysisManageDTO insertManageDTO = manageService.getById(manageId);

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            //处理（企业ID）
            List<Integer> newEntIdList = FormatUtils.commaToList_Integer(entIds);

            //有三种数据：
            //1、原来企业-用户关系不变的数据：不操作
            //2、删除的关系数据：管理员表删除一条记录
            //3、新增的关系数据：管理员表新增一条记录

            //STEP01、取出原有数据（企业ID）
            List<IotEnterpriseManageDTO> originEntObjList = enterpriseRelService.getEnterpriseListByManage(manageId);
            List<Integer> originEntIdList = new ArrayList<>(); //EntId集合


            //STEP02、比较现有数据
            List<IotEnterpriseManageDTO> deleteEntIdList = new ArrayList<>(); //删除的企业ID
            for (IotEnterpriseManageDTO item : originEntObjList) {
                //已经删除的记录
                if (!newEntIdList.contains(item.getEntId())) {
                    deleteEntIdList.add(item);
                }

                originEntIdList.add(item.getEntId());
            }

            List<Integer> addEntIdList = new ArrayList<>();    //新增的企业ID
            for (Integer item : newEntIdList) {
                if (!originEntIdList.contains(item)) {
                    //新增的记录
                    addEntIdList.add(item);
                }
            }

            boolean isNext = true;

            //STEP03、将删除的企业ID数据置为无效（关联表和管理员表两个地方）
            IotEnterpriseManageDTO emRelDTO;
            AnalysisManageDTO manageDTO;
            for (IotEnterpriseManageDTO item : deleteEntIdList) {
                //01、删除关联表数据
                emRelDTO = new IotEnterpriseManageDTO();
                emRelDTO.setDeleteFlag(1);
                emRelDTO.setEntId(item.getEntId());
                emRelDTO.setId(item.getId());
                isNext = enterpriseRelService.updateInfoById(emRelDTO);
                if (!isNext) {
                    break;
                }

                //02、删除管理员表数据
                manageDTO = new AnalysisManageDTO();
                manageDTO.setDeleteFlag(1);
                manageDTO.setEntId(item.getEntId());
                manageDTO.setId(item.getManageId());
                isNext = manageService.updateInfoById(manageDTO);
                if (!isNext) {
                    break;
                }

                //03.删除会员表中的数据（不删除）
            }

            Date date = new Date();
            for (Integer item : addEntIdList) {

                //STEP04、管理员表插入新的记录
                if (insertManageDTO == null) {
                    isNext = false;
                    break;
                }

                //首先判断此用户之前是否存在，后来被禁用了；如果这样的话启用就可以了，无须新增。
                AnalysisManageDTOQuery exsitQuery = new AnalysisManageDTOQuery();
                exsitQuery.setEntId(item);
                exsitQuery.setAdminName(insertManageDTO.getAdminName());
                exsitQuery.setDeleteFlag(1);
                AnalysisManageDTO exsitDTO = manageService.getByQuery(exsitQuery);
                if (exsitDTO != null) {
                    //A、启用删除的管理员
                    AnalysisManageDTO updateDTO = new AnalysisManageDTO();
                    updateDTO.setDeleteFlag(0);
                    updateDTO.setEntId(item);
                    updateDTO.setId(exsitDTO.getId());
                    boolean res = manageService.updateInfoById(updateDTO);

                    //B、启用删除的对应关系
                    if (res) {
                        IotEnterpriseManageDTOQuery updateRelQuery = new IotEnterpriseManageDTOQuery();
                        updateRelQuery.setDeleteFlag(0);
                        updateRelQuery.setW_entId(item);
                        updateRelQuery.setW_manageId(exsitDTO.getId());
                        res = enterpriseRelService.updateInfoByQuery(updateRelQuery);
                    }

                    if (!res) {
                        //如果启用不成功，说明之前没有对应关系（理论上不应该），那么插入一条。
                        IotEnterpriseManageDTO insertRelDTO = new IotEnterpriseManageDTO();
                        insertRelDTO.setIsMain(0);
                        insertRelDTO.setEntId(item);
                        insertRelDTO.setManageId(exsitDTO.getId());
                        insertRelDTO.setAdminName(exsitDTO.getAdminName());
                        insertRelDTO.setAdminId(curr_obj.getId());
                        insertRelDTO.setCreateTime(date);
                        insertRelDTO.setStopFlag(0);
                        insertRelDTO.setDeleteFlag(0);
                        enterpriseRelService.insert(insertRelDTO);
                    }

                    //不用走下面的程序了
                    continue;
                }

                //01、管理员表中插入数据
                insertManageDTO.setId(0);
                insertManageDTO.setEntId(item);
                insertManageDTO.setDepId(0);
                insertManageDTO.setAreaId(0);
                insertManageDTO.setMemLevel(0);
                insertManageDTO.setIsCharge(0);
                insertManageDTO.setIsGroup(1);
                insertManageDTO.setAgentId(0);
                insertManageDTO.setLoginTimes(0);
                insertManageDTO.setIsBindWxapp(0);
                insertManageDTO.setRemark("来源于企业关联");
                insertManageDTO.setCreatePeople(curr_obj.getId());
                insertManageDTO.setCreateTime(date);
                insertManageDTO = manageService.insert(insertManageDTO);
                if (insertManageDTO == null || insertManageDTO.getId() <= 0) {
                    isNext = false;
                    break;
                }

                //02、每增加一名管理员都要向会员表中增加一名会员
                userService.saveAUser(UserTypeEnum.MANAGE.getKey(), insertManageDTO.getId(), insertManageDTO.getMobile(), insertManageDTO.getNickName(), curr_obj.getId(), item);

                //SETP05、[企业-管理员]关联表插入新的记录
                IotEnterpriseManageDTO insertRelDTO = new IotEnterpriseManageDTO();
                insertRelDTO.setIsMain(0);
                insertRelDTO.setEntId(item);
                insertRelDTO.setManageId(insertManageDTO.getId());
                insertRelDTO.setAdminName(insertManageDTO.getAdminName());
                insertRelDTO.setAdminId(curr_obj.getId());
                insertRelDTO.setCreateTime(date);
                insertRelDTO.setStopFlag(0);
                insertRelDTO.setDeleteFlag(0);
                insertRelDTO = enterpriseRelService.insert(insertRelDTO);
                if (insertRelDTO == null || insertRelDTO.getId() <= 0) {
                    isNext = false;
                    break;
                }
            }

            if (isNext) {
                map.put("returnCode", 1);
                map.put("returnMessage", "企业信息关联成功！");
            } else {
                map.put("returnMessage", "企业信息关联失败！");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            map.put("returnMessage", ex.getMessage());
        }

        return map;
    }
    //endregion
}